// package1/pages/apply/apply.js
import service from '../../../utils/request'
const app =getApp()
const citys = {
  浙江: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
  福建: ['福州', '厦门', '莆田', '三明', '泉州'],
};
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl:app.data.url,
    // isDict: app.data.url,
    phone:'',
    columns: [],
    value1:'',
    show:false,
    showSite: false,
    address:'',
    site:'',
    name:'',
    hid:'',
    disabled: false,
    parkNo: '',
    errMsg: '',
    isRead: false,
    visible: false,
    isChoos: false,
    agreement: '',
    fileList: [],
    sfzPort: [],
    sfzNart: [],
    showAdd: false,
    id: '',
  },
  clickCheck(){
    this.setData({
      isChoos: !this.data.isChoos
    })
  },
  readFinish(){
    console.log('阅读完成')
    if(this.data.isRead ==false){
      this.setData({
        isRead: true
      })
    }
   
  },
  onChoose(event) {
    // console.log('event',event.detail)
    this.setData({
      isChoos: event.detail,
    });
  },
  showVisible(){
    this.setData({
      visible: true
    })
  },
  onChange(event) {
    const { picker, value, index } = event.detail;
    picker.setColumnValues(1, citys[value[0]]);
  },
  getAgree(){
    service('POST', '/personal/apply/agreement/view').then((res) => {
      console.log('协议', res)
      let data = res.data
      this.setData({
        agreement: data.html
      })
     
    })
  },
  getSite() {
    service('GET', '/iot/sites').then((res) => {
      console.log('站点', res)
      let dataList =[]
      for (let i =0; i<res.length; i++){
        dataList[i].value = res[i].name
        dataList[i].value = res[i].name
      }
    })
  },
  clickSite(){
    this.setData({ show: true });
  },
  onChangeSite(event){
    const { picker, value, index } = event.detail;
  },
  onClose() {
    this.setData({ visible: false , isRead: false});
  },
  confirmSite(option){
    console.log('confirmSite',option)
    let showAdd = false
    if(option.detail ==0){
       showAdd = true
    }
    this.setData({
      site: option.detail,
      showAdd: showAdd
    })

  },
  confirmArea(option){
    console.log('confirmArea',option)
    this.setData({
      hid: option.detail
    })
  },
  confirmRead(){
    this.setData({
      visible: false,
      isChoos: true
    })
  },
  applyBtn(){
    if(!this.data.isRead){
      this.setData({
        visible: true
      })
      return
    }
    if(this.data.sfzPort.length <1 || this.data.sfzNart.length <1){
      wx.showToast({
        title: '请上传身份证',
        icon: 'none'
      })
      return
    }
    if(this.data.fileList < 1){
      wx.showToast({
        title: '请上传车位产权或一年及以上车位租赁协议',
        icon: 'none'
      })
      return
    }
   
    let phone = this.data.phone, siteId  = this.data.site ?  this.data.site : ''
    let address = siteId ? '' : this.data.address
    let hid = siteId ? '' : this.data.hid
    let name = this.data.name
    let zm = this.data.sfzPort[0].base
    let fm = this.data.sfzNart[0].base
    let sfz = [zm ,fm]
    let fileList = this.data.fileList
    let lng = '104.22'
    let lat = '30.324'
    let parkNo = this.data.parkNo
    var myreg = /^1[3456789]\d{9}$/;
    console.log('phone', phone)
    let propertyCard = []
    fileList.map(item => {
      propertyCard.push(item.base)
    })
    if(hid == '' && siteId == ''){
      let msg = '站点和地址请选填一个'
      wx.showToast({
        title: msg,
        icon: 'none'
      })
      return false
    }
    if(hid && address ==''){
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
     return false}
    if(address && hid ==''){ wx.showToast({
      title: '请选择地区',
      icon: 'none'
    })
    return false}

    if (!myreg.test(phone)) {
        this.setData({
          errMsg: '手机号格式不正确'
        })
      return false
    }else{
      this.setData({
        errMsg: ''
      })
    }
    this.setData({
      disabled: true
    })
    console.log({
      phone, siteId, address, lng, lat, parkNo, name, hid,sfz, propertyCard
    })
    let id =this.data.id
    let data = {phone, siteId, address, lng, lat, parkNo, name, hid,sfz, propertyCard, protocol}
    let msg = '修改'
    let url = '/personal/apply//submit'
    if(id){
      url = '/personal/apply/updata/submit'
      data = {phone, siteId, address, lng, lat, parkNo, name, hid,sfz, propertyCard, protocol, id, msg }
    }
    let protocol  = true
    service('POST', url, data).then((res) => {
      console.log('提交返回', res)
      let icon = 'none'
      if(res.data.code == 0){
       icon = 'none'
       wx.showToast({
         
        title: res.data.msg,
        icon: icon
      })
       setTimeout(() => {
        wx.navigateBack()
       }, 500);
      }else{
        this.setData({
          disabled: false
        })
      }
      wx.showToast({
        title: res.data.msg,
        icon: icon
      })
    })
  },

  afterRead(event) {
    console.log('event', event)
    const { file } = event.detail;
    let name = event.currentTarget.dataset.id
    let that = this
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      header:{
        token: wx.getStorageSync('token'),
        'accept': 'application/json',
      },
      url: this.data.baseUrl+'/file/pile', 
      filePath: file.url,
      name: 'file',
      formData: { user: 'test' },
      success(res) {
        console.log('res',res)
        let data = JSON.parse(res.data)
        console.log(data)
        // 上传完成需要更新 fileList
        
        if(name == 'fileList'){
          var  { fileList = [] } = that.data;
          fileList.push({ ...file, url:that.data.baseUrl+data.file, deletable: true, base: data.file});
        }else{
          var fileList = [{ ...file, url:that.data.baseUrl+data.file, deletable: true, base: data.file}]
        }
        
        if(name =='sfzPort'){
          that.setData({ 
            sfzPort: fileList
           });
        }else if(name == 'sfzNart'){
          that.setData({ 
            sfzNart: fileList
           });
        }else{
          that.setData({ 
            fileList: fileList
           });
        }
        console.log('uploadFile', that.data.fileList)
      },
    })
    
  },
  deletePicSZ(e){
    console.log('删除图片' , e)
    let data = this.data.sfzPort
    data.splice(e.detail.index, 1)
    console.log(data)
    this.setData({
      sfzPort: data
    })
  },
  deletePicSF(e){
    console.log('删除图片' , e)
    let data = this.data.sfzNart
    data.splice(e.detail.index, 1)
    console.log(data)
    this.setData({
      sfzNart: data
    })
  },
  deletePicCQ(e){
    console.log('删除图片' , e)
    let data = this.data.fileList
    data.splice(e.detail.index, 1)
    console.log(data)
    this.setData({
      fileList: data
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.id){
      this.setData({
        id: options.id
      })
      this.fetchData()
    }else{
      this.setData({
        showSite: true
      })
    }
   this.getAgree()
  },
  fetchData(){
    let that = this
    service('POST', `/personal/apply/info/${this.data.id}`).then((res) => {
      console.log('提交返回', res)
      if(res.data.code == 0){
        let info = res.data.personalApplyPile
        let name = info.name
        let parkNo = info.parkNo
        let phone = info.phone
        let propertyCard = JSON.parse(info.propertyCard)
        let fileList = []
        let besa = that.data.baseUrl
        
        for(var index=0; index < propertyCard.length; index++){
          var datas = {}
          console.log(111)
          datas.base = propertyCard[index]
          datas.url = besa+propertyCard[index]
          fileList.push(datas)
          // fileList= [...fileList , datas]
        }
        console.log('fileList',propertyCard.length)
        // propertyCard.map((item, index) => {
        //   fileList[index].base = item
        //   fileList[index].url = besa+item
        // })
        
        let sfzPort = [{base: info.sfz[0], url: besa+info.sfz[0]}]
        let sfzNart = [{base: info.sfz[1], url: besa+info.sfz[1]}]
        let siteId = info.siteId
        let hid = info.hid
        that.setData({
          name: name,
          parkNo: parkNo,
          fileList: fileList,
          sfzPort: sfzPort,
          sfzNart: sfzNart,
          isRead: true,
          showSite: true,
          isChoos: true,
          site: siteId,
          hid: hid,
          phone:phone

        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})